package com.hjf.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.commons.web.servlet.BaseServlet;
import com.commons.po.Customer;
import com.commons.po.DeptPo;
import com.commons.po.PageBean;
import com.commons.po.UserPo;
import com.commons.utils.ConstantUtils;
import com.commons.utils.StringUtils;
import com.hjf.service.DeptPoService;
import com.hjf.service.impl.DeptPoServiceImpl;

public class DeptPoServlet extends BaseServlet {
	DeptPoService deptService=new DeptPoServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String opr=req.getParameter("opr");  //操作符
		String pageIndex=req.getParameter("pageIndex");  //当前页码
		//加载新建、更新页面的数据
		if("add".equals(opr)||"update".equals(opr)){  
			loadData(req,resp,opr,pageIndex);
			
		//把新建、更新的数据存进数据库
		}else if("inadd".equals(opr)||"inupdate".equals(opr)){  
			Customer currUser=this.getCurrUser(req.getSession());
			java.sql.Timestamp currTime=new java.sql.Timestamp(System.currentTimeMillis());
			int row=0;
			if("inadd".equals(opr)){
				row=inAdd(req, currUser, currTime);
			}else if("inupdate".equals(opr)){
				row=inUpdate(req, currUser, currTime);
			}
			PrintWriter out=resp.getWriter();
			if(row>0){
				out.println("<script type='text/javascript'>alert('保存成功');location.href='deptPoServlet?pageIndex="+pageIndex+"';</script>");
			}else{
				out.println("<script type='text/javascript'>alert('保存失败');history.back();</script>");
			}
			
		//  禁用/激活 状态更改	
		}else if("isActive".equals(opr)){  
			DeptPo dept=deptService.findById(StringUtils.str2Integer(req.getParameter("id"),false)).get(0);
			Integer ia=dept.getIsActive();
			String mag="";
			if(ia.equals(1)){
				dept.setIsActive(0);
				mag="禁用";
			}else{
				dept.setIsActive(1);
				mag="激活";
			}
			int row=deptService.updateDeptPo(dept);
			PrintWriter out=resp.getWriter();
			if(row>0){
				out.println("<script type='text/javascript'>alert('"+mag+"成功');location.href='deptPoServlet?pageIndex="+pageIndex+"';</script>");
			}else{
				out.println("<script type='text/javascript'>alert('"+mag+"失败');history.back();</script>");
			}
			
		//加载部门主页面数据 
		}else{  
//			getDeptList(req, resp);//第一种加载数据方式
			
			//第二种加载数据方式，有分页效果
			int index=StringUtils.str2Integer(pageIndex==null?"1":pageIndex,false);
			Integer deptId=StringUtils.str2Integer(req.getParameter("did"),false);
			Map<String, Object> map=null;
			if(deptId!=null){
				map=new HashMap<String, Object>();
				map.put("deptId", deptId);
				req.setAttribute("grandpa",deptService.findById(deptId).get(0).getDeptParent());
			}
			PageBean<DeptPo> pageBean=deptService.findPageByCondition(index, ConstantUtils.PAGE_SIZE, map);
			req.setAttribute("pageBean", pageBean);
			req.getRequestDispatcher("/jsp/sys/dept/dept_list.jsp").forward(req, resp);
		}
	}
	
	/*
	 * 
	 * 展示dept_list数据
	 * 没有分页效果
	 * 当点击父级项时展示出子项
	 */
	private void getDeptList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<DeptPo> list=deptService.findByCondition();
		Integer deptId=StringUtils.str2Integer(req.getParameter("did"),false);
		List<Integer> idList=new ArrayList<Integer>();
		if(deptId!=null){
			List<DeptPo> sonList=deptService.findByDeptParent(deptId);
			if(sonList!=null&&sonList.size()>0){
				for(DeptPo d:sonList){
					idList.add(d.getDeptId());
				}
			}
			Integer parentId=null;
			do{
				parentId=deptService.findById(deptId).get(0).getDeptParent();
				if(parentId!=null){
					List<DeptPo> otherList=deptService.findByDeptParent(parentId);
					if(otherList!=null&&otherList.size()>0){
						for(DeptPo d:otherList){
							idList.add(d.getDeptId());
						}
					}
					deptId=parentId;
				}
			}while(parentId!=null);
		}
		for(int i=0;i<list.size();i++){
			DeptPo dept=list.get(i);
			if(dept.getDeptParent()!=null){
				boolean isFlag=true;
				if(idList.size()>0){
					for(Integer id:idList){
						if(dept.getDeptId().equals(id)){
							isFlag=false;
						}
					}
					if(isFlag){
						list.remove(i);
						i=i-1;
					}
					isFlag=true;
				}else{
					list.remove(i);
					i=i-1;
				}
			}
		}
		req.setAttribute("list", list);
		req.getRequestDispatcher("/jsp/sys/dept/dept_list.jsp").forward(req, resp);
	}
	
	/*新建部门，把数据插到数据库中*/
	private int inAdd(HttpServletRequest req, Customer currUser, java.sql.Timestamp currTime) {
		DeptPo dept=new DeptPo();
//				dept.setDeptId(deptId);
		dept.setDeptName(req.getParameter("name"));
		dept.setDeptParent(StringUtils.str2Integer(req.getParameter("parentId"),false));
		dept.setCreatedId(currUser.getCustomer_id());
		dept.setCreatedDate(currTime);
		dept.setUpdateId(currUser.getCustomer_id());
		dept.setUpdateDate(currTime);
		dept.setIsActive(1);
		dept.setDeptIntroduce(req.getParameter("description"));
		return deptService.saveDeptPo(dept);
	}
	
	/*修改部门，更新数据库数据*/
	private int inUpdate(HttpServletRequest req, Customer currUser, java.sql.Timestamp currTime) {
		Integer id=StringUtils.str2Integer(req.getParameter("id"), false);
		DeptPo dept=deptService.findById(id).get(0);
		dept.setDeptName(req.getParameter("name"));
		dept.setDeptParent(StringUtils.str2Integer(req.getParameter("parentId"),false));
		dept.setUpdateId(currUser.getCustomer_id());
		dept.setUpdateDate(currTime);
		dept.setDeptIntroduce(req.getParameter("description"));
		return deptService.updateDeptPo(dept);
	}
	
	/*新建或修改部门时，需加载的数据*/
	private void loadData(HttpServletRequest req, HttpServletResponse resp,String opr,String pageIndex) throws ServletException, IOException {
		List<DeptPo> list=deptService.findByCondition();
		if("add".equals(opr)){
			req.setAttribute("login", list);
			req.getRequestDispatcher("/jsp/sys/dept/dept_save.jsp").forward(req, resp);
		}else{
			Integer id=Integer.parseInt(req.getParameter("id"));
			DeptPo deptNow=deptService.findById(id).get(0);
			req.setAttribute("deptPo", deptNow);
			for(int i=0;i<list.size();i++){
				DeptPo dept=list.get(i);
				if(dept.getDeptId().equals(id)){
					list.remove(i);
					i=i-1;
				}
			}
			req.setAttribute("login", list);
			req.getRequestDispatcher("/jsp/sys/dept/dept_save.jsp?pageIndex="+pageIndex).forward(req, resp);
		}
	}

}
